import React, { Component } from 'react'
import { Switch, Route, Redirect } from 'react-router-dom'
import { connect } from 'react-redux'
import { NavBar } from 'antd-mobile'
import Cookies from 'js-cookie'
import { getRedirectTo } from '../../utils'
import { getUser } from '../../redux/action'
import NavFooter from '../../compoments/nav-footer/nav_footer'

import './main.less'

class Main extends Component{
    componentDidMount() {
        const userId = Cookies.get('userId')
        const { _id } = this.props.user
        if (userId && !_id) {
            this.props.getUser()
        }
    }
    render() {
    const userId = Cookies.get('userId')
    if (!userId)  return <Redirect to='login'/>

    const { _id, userType, header} = this.props.user
    if (!_id) {
        return null
    }else {
        let path = this.props.location.pathname
        if (path === '/'){
            path = getRedirectTo(userType, header)
            return <Redirect to={path}/>
        }
    }

    const path = this.props.location.pathname
    const route = this.props.routes.find(route => path === route.path)
    let footerNav = []
    if (route) {
        if (route.path === '/jobSeekerInfo' || route.path === '/bossInfo') {

        }else {
            this.props.routes.map(route => {
                if (userType === 'boss') {
                    if (route.footerNav && route.path !== '/jobSeeker') {
                        return footerNav.push(route)
                    }
                }else {
                    if (route.footerNav && route.path !== '/boss' ) {
                        return footerNav.push(route)
                    }
                }
            })
        }
    }
    return(
        <div className='main'>
            {
                route ? <NavBar className='main-header'>{route.title}</NavBar> : null
            }
            <Switch>
                {this.props.routes.map( route => {
                     return <Route key={route.name} path={route.path} exact render={props =>
                            <route.component {...props} routes={route.routes}/>
                        } />
                })}
            </Switch>
            {
                footerNav.length>0 ? <NavFooter footerNav ={ footerNav } unReadCount = { this.props.unReadCount} /> : null
            }
        </div>
    )
}
}



export default connect(
    state=>({
        user:state.user,
        unReadCount:state.chat.unReadCount
    }),
    { getUser }
)(Main)
